import axios from 'axios'
import router from '@/router'
import { ls } from '@/utils/storage'

class Request {
  constructor(config) {
    this.instance = axios.create(config)
    this.interceptors = config.interceptors
    this.tokenMap = {}
    this.instance.interceptors.request.use(
      this.interceptors?.requestInterceptor,
      this.interceptors?.requestInterceptorCatch
    )
    this.instance.interceptors.response.use(
      this.interceptors?.responseInterceptor,
      this.interceptors?.responseInterceptorCatch
    )
    // 所有实例都共享的拦截器
    this.instance.interceptors.request.use((config) => {
      return config
    })
    this.instance.interceptors.response.use((config) => {
      return config
    })
  }

  request(config) {
    return new Promise((resolve, reject) => {
      // 单个请求对请求config的处理
      if (config.interceptors?.requestInterceptor) {
        config = config.interceptors.requestInterceptor(config)
      }
      if (config.token) {
        if (this.tokenMap[config.token]) {
          this.tokenMap[config.token].cancel()
        }
        this.tokenMap[config.token] = axios.CancelToken.source()
        config = Object.assign(
          {
            cancelToken: this.tokenMap[config.token].token,
          },
          config
        )
      }
      this.instance
        .request(config)
        .then((res) => {
          // 单个请求对数据的处理
          if (config.interceptors?.responseInterceptor) {
            res = config.interceptors.responseInterceptor(res)
          }
          // 将结果resolve返回出去
          resolve(res)
        })
        .catch((err) => {
          const {response} = err
          if(response?.status === 403){
            router.replace('/apply')
          }
          else if(response?.status === 407 ||err?.code === 407){
            router.replace('/nopermission')
          }
          // else if(response.status === 405){
          //   router.replace('/error')
          // }
          if(response?.status === 401){
            location.href ="https://passport2.chaoxing.com/login?refer=" + encodeURIComponent(`${import.meta.env.VITE_BASE_URL}`)
          }
          // router.push('/error')
            reject(err)
            return err
        })
    })
  }

  get(config) {
    return this.request({ ...config, method: 'GET' })
  }

  post(config) {
    return this.request({ ...config, method: 'POST' })
  }

  delete(config) {
    return this.request({ ...config, method: 'DELETE' })
  }

  patch(config) {
    return this.request({ ...config, method: 'PATCH' })
  }

  put(config) {
    return this.request({ ...config, method: 'PUT' })
  }
}

const request = new Request({
  baseURL: '/api/ancient',
  timeout: 5000,
  retry: 3,
  rettyDelay:1000,
  // baseURL: '/api', //mock test
  interceptors: {
    requestInterceptor: (config) => {
      const token = ls.get('token')
      if (token) {
        config.headers['token'] = token
      }
      //判断请求头类型
      if (config.headers['data-type'] == 'file') {
        config.headers['Content-Type'] = 'multipart/form-data'
      } else {
        config.headers['Content-Type'] = 'application/json'
      }
      return config
    },
    responseInterceptor: (res) => {
      const {
        data,
        config: { method, url },
        status
      } = res
      // console.log('data', data)
      const { code, msg, message } = data
      if (code == null && status === 200) {
        return { data, headers: res.headers }
      }
      // 请求成功
      else if (code === 200) {
        return data
      }
      // 其它情况
      else {
        // console.log(config)
        const error = {
          type: 'error',
          title: '操作失败',
          method,
          url,
          status,
          code,
          message: msg?.length > 30 ? '请求出错啦,请稍后重试！' : message,
        }
        // if (code == 401) {
        //   // logout();
        //   location.href ="https://passport2.chaoxing.com/login?refer=" + encodeURIComponent(`${import.meta.env.VITE_BASE_URL}`)
        //   error.message = '登陆已过期，即将退出，请重新登陆！'
        // } else if (code == 403) {
        //   // console.log(res)
        //   // error.message = '暂无权限，即将退出！'
        //   error.message = data.message
        //   router.replace('/nopermission')
        // }
        return Promise.reject(error)
      }
    },
  },
})

export default request
